<script lang="tsx">
import {defineComponent, nextTick, ref, watch} from "vue";
import {useDictStore} from "/@/store/modules/dict";
import {ElSelect, ElOption} from "element-plus"
import {SelectProps, selectProps} from "/@/components/Base/BaseSelect/ts";

export default defineComponent({
    name: "BaseSelect",
    props: selectProps,
    setup(props: SelectProps, {expose, emit, slots}) {
        const options = ref<any[]>([])
        watch(
            () => props.dict,
            async (newValue) => {
                if (newValue) {
                    const dictStore = useDictStore()
                    let res = await dictStore.getDict(newValue);
                    options.value = res

                }
            },
            {immediate: true}
        );

        watch(
            () => props.options,
            async (newValue: any) => {
                if (newValue && newValue.value) {
                    options.value = newValue.value
                } else if (newValue) {
                    options.value = newValue
                }

            },
            {immediate: true}
        );

        const render = () => {
            let key = props.props.value || 'value';
            let label = props.props.label || 'label'
            let enabled = props.props.disabled || 'disabled'
            return <ElSelect class="w-full">
                {
                    options.value.map((res) => {
                        if (props.props.disabled && typeof props.props.disabled === 'function') {
                            let fn = props.props.disabled as Function
                            res.disabled = fn.call(res, res)
                            enabled = 'disabled'
                        }
                        let value = res[key]
                       
                        if (props.toNumber) {
                            value = Number.parseInt(res[key] as string)
                        }else if(props.toStr && res[key]){
                            value = res[key].toString()
                        }
                        return <ElOption key={value} value={value} label={res[label]} disabled={res[enabled]}>
                        </ElOption>
                    })
                }
            </ElSelect>
        }
        return render
    }
})
</script>

<style scoped>

</style>